<?php
namespace App\Http\Controllers\Login;
use App\Http\Controllers\Controller;
use App\Models\VoidsModels\Voids;
use Illuminate\Http\Request;
use App\Http\Controllers\ApiBaseController;
use App\Components\Tools;
use App\Components\DyToools;
use App\Models\DyModels\Douyin;

class VoidController extends ApiBaseController{
	
	private $url="";
	function __construct(Request $request) {
		parent::__construct($request);
        $this->parames = $request->all();
		$this->url=Tools::getOneconfig("/config/third.json",array('qiniu','qnUrl'));
	}
	
	//审核列表
	function index(){
		return view('/login/void/index',['void_list_data'=>true]);
	}
	
	//视频列表
	function info(){
		return view('/login/void/info',['void_list_info'=>true]);
	}
	
	//视频列表拉取
	function searchAll(){
		$voids=new Voids();
		$result=$voids->getPageDataAll($this->params);
		echo json_encode($result);
	}
	
	//未审核视频数据拉取
	function search(){
		$voids=new Voids();
		$result=$voids->getPageData($this->params);
		echo json_encode($result);
	}
	
	//审核操作
	function save(){
		$voids=new Voids();
		$kid=isset($this->parames['kid']) && intval($this->parames['kid'])>0 ? intval($this->parames['kid']) : $this->returnJson(1,"数据错误");
		$status=isset($this->parames['status']) ? intval($this->parames['status']) : $this->returnJson(1,"数据错误");
		$remark=isset($this->parames['remark']) ? $this->parames['remark'] : '';
		
		//审核不通过
		if($status==-1){
			$data=array(
				'status'=>-1,
				'update_time'=>date('Y-m-d H:i:s',time()),
				'remark'=>$remark,
				'operator'=>session('user')[0]['admin_name'],
			);
			$re=$voids->updateAll($kid,$data);
			
			$re ? $this->returnJson(0,'操作成功') : $this->returnJson(1,'操作失败');
		}else{//审核通过    异步操作
			
			//查询该视频需上传的信息
			$videoData=$voids->selectVideo($kid);
			!$videoData || $videoData['status']!=0 ? $this->returnJson(1,'视频不存在') : '';
			
			//查询该视频用户的授权信息
			$token=$voids->selectToken($videoData['open_id']);
			!$token ? $this->returnJson(1,"未授权或授权已过期") : '';
			
			//修改状态为3 异步上传抖音中
			$result=$voids->updateAll($kid,['status'=>3,'operator'=>session('user')[0]['admin_name']]);
			$result ? '' : $this->returnJson(1,'操作失败');
			
			//提交到curl异步处理
			$url=$_SERVER['HTTP_HOST']."/void/list/saveVideo";
			$this->postJson($url,['kid'=>$kid,'name'=>session('user')[0]['admin_name']]);
			
			$this->returnJson(0,"操作成功");
		}
		/*}else{//审核通过   同步操作
			//查询该视频需上传的信息
			$videoData=$voids->selectVideo($kid);
			!$videoData ? $this->returnJson(1,'视频不存在') : '';
			
			//上传图片
			$img_id=$this->upImgToDY($videoData['cover'],$videoData['open_id']);
			
			//查询该视频用户的授权信息
			$token=$voids->selectToken($videoData['open_id']);
			!$token ? $this->returnJson(1,"请先授权该账号") : '';
			
			//上传视频
			$video_id=$this->videoUpToDY($videoData['share_url'],$token);
			
			//发布视频
			$video_title=$videoData['title'].$videoData['talk'];
			$this->videoFbToDY($kid,$token,$video_id,$img_id,$video_title);
		}*/
	}
	
	//上传视频封面到抖音
	function upImgToDY($imgUrl,$open_id){
		$img_id=false;
		
		$DouyinModel=new Douyin();
		$DyToools=new DyToools();
		
		//查询该视频用户的授权信息
		$token=$DouyinModel->oneTokenInfo($open_id);
		!$token ? $this->returnJson(1,"账号未授权或已过期") : '';
		
		$imageUrl=$this->url ."/".$imgUrl;
		$first=explode('/',$imageUrl);
		
		$name=isset($first[1]) ? end($first) : $this->returnJson(1,'图片不存在');
		$imgList=$DyToools->imageUpload($token['access_token'],$open_id,$imageUrl,$name);
		if(isset($imgList['data']['error_code']) && $imgList['data']['error_code'] == 0){
			
			
			//取出图片地址返回
			$img_id=$imgList['data']['image']['image_id'];
			
			
		}elseif(isset($imgList['data']['error_code']) && ($imgList['data']['error_code'] == 10008 || $imgList['data']['error_code']==2190008) ){
			
			
			// access_token 过期
			$tokenOne=$DyToools->refresh_token($token['refresh_token']);
			if( isset($tokenOne['data']['error_code']) && $tokenOne['data']['error_code']==0 ){
				
				
				//更新数据库的 access_token
				$DouyinModel->upToken($tokenOne['data'],$open_id);
				//重新调用上传图片
				$this->upImgToDY($imgUrl,$open_id);
				
				
			}elseif( isset($tokenOne['data']['error_code']) && $tokenOne['data']['error_code']==10010 ){
				
				
				// refresh_token 过期
				$tokenTwo=$DyToools->renew_refresh_token($tokens['refresh_token']);
				if( isset($tokenTwo['data']['error_code']) && $tokenTwo['data']['error_code']==0 ){
					
					
					//更新数据库的 refresh_token
					$DouyinModel->upRef($tokenTwo['data'],$open_id);
					//重新调用上传图片
					$this->upImgToDY($imgUrl,$open_id);
					
					
				}else{
					$DouyinModel->upTokenStatus($open_id);
					$this->returnJson(1,'授权已过期，请重新授权！');
				}
			}
		}
		return $img_id ? $img_id : $this->returnJson(1,'上传封面失败！');
	}
	
	/**上传视频到抖音
	*	$videoUrl  视频源地址		$token 	授权信息
	*/
	function videoUpToDY($videoUrl,$token){
		$video_id=false;
		
		$DyToools=new DyToools();
		
		$videoUrl=$this->url ."/".$videoUrl;
		$first=explode('/',$videoUrl);
		
		$name=isset($first[1]) ? end($first) : $this->returnJson(1,'视频不存在');
		$voidList=$DyToools->videoUpload($token['access_token'],$token['open_id'],$videoUrl,$name);
		if(isset($voidList['data']['error_code']) && $voidList['data']['error_code'] == 0){
			$video_id=$voidList['data']['video']['video_id'];
		}
		return $video_id ? $video_id : $this->returnJson(1,'上传视频失败！');
	}
	
	/**发布视频修改视频信息
	*	$kid  本库的视频id		$token  授权信息		$video_id  上传抖音的视频ID	
	*	$img_id  上传抖音的封面ID			$video_title  视频标题+话题
	*/
	function videoFbToDY($kid,$token,$video_id,$img_id,$video_title){
		$result=false;
		$voids=new Voids();
		$DyToools=new DyToools();
		$re=$DyToools->videoCreate($token['access_token'],$token['open_id'],$video_id,$img_id,$video_title);
		if(isset($re['extra']['error_code']) && $re['extra']['error_code'] == 0){
			//发布成功 修改视频信息 等待抖音审核
			$data=array(
				'item_id'=>$re['data']['item_id'],
				'status'=>1,
				'create_time'=>date('Y-m-d H:i:s',time()),
				'operator'=>session('user')[0]['admin_name'],
			);
			$result=$voids->updateAll($kid,$data);
		}
		$result ? $this->returnJson(0,'提交抖音审核成功') : $this->returnJson(1,'提交抖音审核失败');
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	//post请求
	function postJson($url, $data = array()){
		//初始化
		$curl = curl_init();
		//设置抓取的url
		curl_setopt($curl, CURLOPT_URL, $url);
		//设置头文件的信息作为数据流输出
		curl_setopt($curl, CURLOPT_HEADER, 0);
		//超时时间
		curl_setopt($curl, CURLOPT_TIMEOUT,1);
		//设置获取的信息以文件流的形式返回，而不是直接输出。
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
		//设置post方式提交
		curl_setopt($curl, CURLOPT_POST, 1);
		//设置post数据
		curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); //不验证证书下同
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
		//执行命令
		$json = curl_exec($curl);
		//关闭URL请求
		curl_close($curl);
	}
	
	
	
	
	
	//获取用户信息测试
	function getUserInfo(){
		$DouyinModel=new Douyin();
		$partner_id=2;
		$tokens=$DouyinModel->userTokenInfo($partner_id);
		if(!isset($tokens['open_id'])){
			echo "该账号尚未授权！";exit;
		}
		$DyToools=new \App\Components\DyToools();
		$data=$DyToools->getUserInfo($tokens['open_id'],$tokens['access_token']);
		if($data['error_code']==0){
			//取到用户信息
			echo "<pre/>";print_r($data);
		}
		elseif($data['error_code']==10008 || $data['error_code']==2190008){
			// access_token 过期
			$data=$DyToools->refresh_token($tokens['refresh_token']);
			if($data['error_code']==0){
				//更新数据库的 access_token
				$DouyinModel->upToken($data);
			}elseif($data['error_code']==10010){
				// refresh_token 过期
				$data=$DyToools->renew_refresh_token($tokens['refresh_token']);
				if($data['error_code']==0){
					
				}else{
					echo "请重新授权";
				}
			}
		}
	}
}